/* 
 @description: 寄件JS

 @author: 韦淇霰

 @update: 2021年9月9日23:11:35
 */
 var token=localStorage.getItem('mytoken')
    const add= document.getElementById('add'),
    input =document.querySelector('input'),
    back = document.querySelector('.back'),
    box = document.querySelector('.box'),
    submit = document.getElementById('submit'),
    closes = document.getElementById('closes'),
    search = document.querySelector('.Search'),
    jjname = document.getElementById('jjname'),
    jjphone = document.getElementById('jjphone'),
    jjaddress = document.getElementById('jjaddress'),
    sjname = document.getElementById('sjname'),
    sjphone = document.getElementById('sjphone'),
    sjaddress = document.getElementById('sjaddress'),
    smtime = document.getElementById('smtime'),
    table = document.getElementById('tab');
    const anniu = document.querySelector('.ulTag');
    const sou = document.querySelector('#sou');


    //模态框拖拽
    //1.鼠标按下的时候，获得鼠标在盒子内的坐标
    back.addEventListener('mousedown',function(e){
        var x = e.pageX - box.offsetLeft;
        var y = e.pageY - box.offsetTop;
        //2.鼠标移动的时候，把鼠标在页面中的坐标 减去 鼠标在盒子中的坐标，得到盒子的left和top
        document.addEventListener('mousemove',move)  
        function move(e) {
            box.style.left = e.pageX - x +'px';
            box.style.top = e.pageY - y + 'px';
        }
        //3.鼠标弹起，就让鼠标移动事件移除
        document.addEventListener('mouseup',function(){
            document.removeEventListener('mousemove',move);
        })
    })

    getList();
        
    //搜索
    function getList(keyname='') {
        $.ajax({
        url: `http://127.0.0.1:7001/api/mail?keyname=${keyname}`,
        method: "GET",
        success: function(res) {
            console.log(res);
            localStorage.setItem('ddtotal',res.count);
            console.log(ddtotal);
            const totalss = Math.ceil(res.count / 8);
            localStorage.setItem('totalss',totalss);
            console.log(totalss);
            if(res.code === 0){
                for (var i = 0; i < res.data.length; i++) {
                    const tr = document.createElement('tr');
                    for (let data in res.data[i]) {
                    const td = document.createElement("td");
                        td.innerHTML = res.data[i][data]
                        tr.appendChild(td);
                      
                        if(data === 'ctime_mail'){
                            let time_d = res.data[i].ctime_mail;
                            var times = new Date(parseInt(time_d)).toLocaleString();
                            td.innerHTML=times;
                        }
                        if(data === 'time_mail'){
                            let time_ds = res.data[i].time_mail;
                            var time_mail = new Date(parseInt(time_ds)).toLocaleString();
                            td.innerHTML=time_mail;
                        }
                        
                    }
                    const lasttd = document.createElement('td');
                    lasttd.innerHTML  = `<button type='button'  name="updata" class="up"  id='${res.data[i].id}'><i class="fa fa-wrench" aria-hidden="true"></i> 修改</button>
                    <button type='button' class="btn" name="delete" id='${res.data[i].id}'><i class="fa fa-trash" aria-hidden="true"></i> 删除</button>`
                    tr.appendChild(lasttd)
                    tr.id = res.data[i].id;
                    table.appendChild(tr);
                    // tr.innerHTML = ''
                }

            }    
        }           
    }
)}

    //删除
    function DelCa(id){
        $.ajax({
        url:`http://127.0.0.1:7001/api/mail/${id}`,
        method:"delete",
        data:{
            id
        },
        success:function(res){
            window.location.reload();
        },
        error:()=>{
            console.log(1);
        }
    })
    }
    //编辑
    function EditCa(name_mail,  phone_mail, address_mail,jname_mail,jphone_mail,jaddress_mail,time_mail,id){
        $.ajax({
        url:`http://127.0.0.1:7001/api/mail/${id}`,
        method:"put",
        data:{
            name_mail,
            phone_mail,
            address_mail,
            jname_mail,
            jphone_mail,
            jaddress_mail,
            time_mail,
            id
        },
        success:function(res){
            if(res.code === 0){
            window.location.reload();
            closeBack();  
            }else{
                alert(res.msg);
            }
        }
    })
    }
    //获取详情
    function getInfo(id){
        $.ajax({
        url:`http://127.0.0.1:7001/api/mail/${id}`,
        method:"get",
        success: function(res) {
            console.log(res.data);
        //    const fwb = document.querySelector('.w-e-text');
        //    console.log(fwb);
        console.log(res.data);
      
            if(res.code === 0){ 
                jjname.value = res.data.name_mail;
                jjphone.value = res.data.phone_mail;
                jjaddress.value = res.data.address_mail;
                sjname.value = res.data.jname_mail;
                sjphone.value = res.data.jphone_mail;
                sjaddress.value = res.data.jaddress_mail;
             
            }else{
                alert(res.msg)
                
            }    
      
        }
        })
    }
    let ida=0;
    //通过事件委托操作 删除和编辑
    table.onclick = function(e){
        if(e.target.className === 'btn'){
            const flag = confirm('确定删除吗');
            if(flag==true){
                DelCa(e.target.id);
            }
        }else if(e.target.className === 'up'){
            back.style.display = 'block';
            const id  = e.target.id;
               ida = id;
            getInfo(id);
            console.log(ida);
        }
    }
    //搜索按钮
    search.onclick = function(){
        getList(sou.value);
        console.log(sou.value);
        table.innerHTML = `<tr class="tab_a">
                                <th>ID</th>
                                <th>订单号</th>
                                <th>寄件人姓名</th>
                                <th>寄件人电话</th>
                                <th>寄件人地址</th>
                                <th>收件人姓名</th>
                                <th>收件人号码</th>
                                <th>收件人地址</th>
                                <th>收件人上门时间</th>
                                <th>下单时间</th>
                                <th>操作</th>
                            </tr>`
        function sss(keyname=''){
            $.ajax({
                url: `http://127.0.0.1:7001/api/mail?keyname=${keyname}`,
                method: "get",
                success: function(res) {
                    console.log(res);
                    const numss = Math.ceil(res.count / 8);
                    console.log(numss);
                    const slp = new SimplePagination(numss);
                    slp.init({
                        container: '.boxs',
                        maxShowBtnCount: 3,
                        onPageChange: state => {
                            getPage(state.pageNumber);
                        }
                    })
                }
            })
            }
            sss(sou.value);
    }
    //取消按钮
    closes.onclick = function(){
        closeBack();
    }
    function closeBack(){
        jjname.value = '';
        jjphone.value = '';
        jjaddress.value = '';
        sjname.value = '';
        sjphone.value = '';
        sjaddress.value = '';
        back.style.display = 'none';
    }
    //编辑提交按钮
    submit.onclick = function(){
        // const a = editor.txt.text();
        // console.log(a);
        EditCa(
               jjname.value,
               jjphone.value,
               jjaddress.value,
               sjname.value,
               sjphone.value,
               sjaddress.value ,
               smtime.value,
                ida
        )
        // console.log(sjname.value,sjphone.value,sjaddress.value);
}
      //富文本
    //   const E = window.wangEditor;
    //   const editor = new E('#content');
    //   editor.create();
      
     //分页
// function getPage(page) {
//     $.ajax({
//     url: `http://127.0.0.1:7001/api/mail?page=${page}`,
//     method: "get",
//     headers:{
//         token
//       },
//     success: function(res) {

//         const ul =document.querySelector('.ulTag');
//         const tab=document.querySelector('#tab');
//         tab.innerHTML='';
//         ul.innerHTML='';
//         const tr=document.createElement('tr')
//         table.innerHTML =  `<tr class="tab_a">
//                                 <th>ID</th>
//                                 <th>订单号</th>
//                                 <th>寄件人姓名</th>
//                                 <th>寄件人电话</th>
//                                 <th>寄件人地址</th>
//                                 <th>收件人姓名</th>
//                                 <th>收件人手机号码</th>
//                                 <th>收件人地址</th>
//                                 <th>收件人上门时间</th>
//                                 <th>下单时间</th>
//                                 <th>操作</th>
//                             </tr>`
//         for (var i = 0; i < res.data.length; i++) {
//             const tr = document.createElement('tr');
//             for (let data in res.data[i]) {
//                 const td = document.createElement("td");
//                 td.innerHTML = res.data[i][data]
//                 tr.appendChild(td);
//                 // console.log(data);
//                 if(data === 'ctime_mail'){
//                     // console.log(11111);
//                     let time_d = res.data[i].ctime_mail;
//                     var times = new Date(parseInt(time_d)).toLocaleString();
//                     td.innerHTML=times;
//                     console.log(times);
//                 }
//                 if(data === 'time_mail'){
//                     // console.log(11111);
//                     let time_ds = res.data[i].time_mail;
//                     var time_mail = new Date(parseInt(time_ds)).toLocaleString();
//                     td.innerHTML=time_mail;
//                     console.log(time_mail);
//                 }
//             }
            
//         }
//         for(const item of res.data){
//             console.log(item);
//             const tr=document.createElement('tr');
//             tr.innerHTML=`<td>${item.id}</td>
//                 <td>${item.order_mail}</td>
//                 <td>${item.name_mail}</td>
//                 <td>${item.phone_mail}</td>
//                 <td>${item.address_mail}</td>
//                 <td>${item.jname_mail}</td>
//                 <td>${item.jphone_mail}</td>
//                 <td>${item.jaddress_mail}</td>
//                 <td>${time_mail}</td>
//                 <td>${times}</td>
//                 <td><button type='button' name="updata" class="up"  id='${item.id}'><i class="fa fa-wrench" aria-hidden="true"></i> 修改</button>
//                 <button type='button' class="btn" name="delete" id='${item.id}'><i class="fa fa-trash" aria-hidden="true"></i> 删除</button></td>
//            `
//            table.appendChild(tr)
//         }
//         getInfor(page)

//     },
//     error:()=>{
//        alert('没有找到id');
//     }
// }
// )}
// function getInfor(page=1){
// $.ajax({
//     url: `http://127.0.0.1:7001/api/mail?page=${page}`,
//     method: "get",
//     headers:{
//         token
//       },
//     success: function(res) {
//         console.log(res.data);
//         const ul =document.querySelector('.ulTag');
//         const num = Math.ceil(res.count / 8);
//         console.log(num);
//         for(let i=0;i<num;i++){
//             const li = document.createElement('li');
//             ul.appendChild(li);
//             li.innerHTML = `<button type="button" class="dianji">${i+1}</button>`
           
//         } 
//         const dj = document.querySelectorAll('.dianji');
//         for(const key of dj)
//         {
            
//             key.onclick = function(){
//                 getPage(key.innerHTML);
                
//                 // window.location.reload();
//             }
//         }
//     }
// })
// }
// getInfor();


//分页
function getPage(page) {
    $.ajax({
    url: `http://127.0.0.1:7001/api/mail?page=${page}`,
    method: "get",
    headers:{
        token
      },
    success: function(res) {
        const ul =document.querySelector('.ulTag');
        const tab=document.querySelector('#tab');
        tab.innerHTML='';
        // ul.innerHTML='';
        const tr=document.createElement('tr')
        table.innerHTML =  `<tr class="tab_a">
                                <th>ID</th>
                                <th>订单号</th>
                                <th>寄件人姓名</th>
                                <th>寄件人电话</th>
                                <th>寄件人地址</th>
                                <th>收件人姓名</th>
                                <th>收件人号码</th>
                                <th>收件人地址</th>
                                <th>收件人上门时间</th>
                                <th>下单时间</th>
                                <th>操作</th>
                            </tr>`
        for (var i = 0; i < res.data.length; i++) {
            const tr = document.createElement('tr');
            for (let data in res.data[i]) {
                const td = document.createElement("td");
                td.innerHTML = res.data[i][data]
                tr.appendChild(td);
                if(data === 'ctime_mail'){
                    let time_d = res.data[i].ctime_mail;
                    var times = new Date(parseInt(time_d)).toLocaleString();
                    td.innerHTML=times;
                }
                if(data === 'time_mail'){
                    // console.log(11111);
                    let time_ds = res.data[i].time_mail;
                    var time_mail = new Date(parseInt(time_ds)).toLocaleString();
                    td.innerHTML=time_mail;
                }
            }
            
        }
        for(const item of res.data){
            const tr=document.createElement('tr');
            tr.innerHTML=`<td>${item.id}</td>
                <td>${item.order_mail}</td>
                <td>${item.name_mail}</td>
                <td>${item.phone_mail}</td>
                <td>${item.address_mail}</td>
                <td>${item.jname_mail}</td>
                <td>${item.jphone_mail}</td>
                <td>${item.jaddress_mail}</td>
                <td>${time_mail}</td>
                <td>${times}</td>
                <td><button type='button' name="updata" class="up"  id='${item.id}'><i class="fa fa-wrench" aria-hidden="true"></i> 修改</button>
                <button type='button' class="btn" name="delete" id='${item.id}'><i class="fa fa-trash" aria-hidden="true"></i> 删除</button></td>
           `
           table.appendChild(tr)
        }

    },
    error:()=>{
       alert('没有找到id');
    }
}
)}
class SimplePagination {
    constructor(totalPageCount) {
        if (!totalPageCount) return
        this.state = {
            pageNumber: 1,
            totalPageCount
        }
    }

    init(paramsObj) {
        let state = this.state
        // 页面元素的外部容器
        state.container = paramsObj.container || 'body'
        // 不包括开头和结尾的两个固定按钮外，中间最多展示几个数字页码按钮
        state.maxShowBtnCount = paramsObj.maxShowBtnCount || 5
        // 所有的页码元素，包括上一页、下一页
        state.pCName = paramsObj.pCName || 'page-li',
            // 当选中页码时添加的类名class
            state.activeCName = paramsObj.activeCName || 'page-active',
            // 代表页码数字的属性
            state.dataNumberAttr = paramsObj.dataNumberAttr || 'data-number',
            // 上一页 按钮的类名class
            state.prevCName = paramsObj.prevCName || 'page-prev',
            // 下一页 按钮的类名class
            state.nextCName = paramsObj.nextCName || 'page-next',
            // 禁用 上一页 按钮时给此按钮添加的类名class
            state.disbalePrevCName = paramsObj.disbalePrevCName || 'no-prev',
            // 禁用 下一页 按钮时给此按钮添加的类名class
            state.disbaleNextCName = paramsObj.disbaleNextCName || 'no-next',
            // 不包括 上一页 下一页 省略号 按钮的页码元素类名
            state.pageNumberCName = paramsObj.pageNumberCName || 'page-number'
        // 触发切换页面的事件
        state.swEvent = paramsObj.swEvent || 'click'
        // 切换页面时调用的函数
        state.onPageChange = paramsObj.onPageChange
        // 当需要省略符号占位时，确定 active的位置
        state.totalPageCount > state.maxShowBtnCount + 2 && (state.activePosition = Math.ceil(state.maxShowBtnCount / 2))
        this.renderPageDOM()
    }

    switchPage() {
        let state = this.state
        let pCNameList = this.selectorEle('.' + state.pCName, true)
        let pageNumber
        pCNameList.forEach(item => {
            item.addEventListener(state.swEvent, e => {
                const currentPageEle = e.target
                if (this.hasClass(currentPageEle, state.activeCName)) return
                let dataNumberAttr = currentPageEle.getAttribute(state.dataNumberAttr)
                if (dataNumberAttr) {
                    // 点击 数字 按钮
                    pageNumber = +dataNumberAttr
                } else if (this.hasClass(currentPageEle, state.prevCName)) {
                    // 点击 上一页 按钮
                    state.pageNumber > 1 && (pageNumber = state.pageNumber - 1)
                } else if (this.hasClass(currentPageEle, state.nextCName)) {
                    // 点击 下一页 按钮
                    state.pageNumber < state.totalPageCount && (pageNumber = state.pageNumber + 1)
                }
                pageNumber && this.gotoPage(pageNumber)
            })
        })
    }
    gotoPage(pageNumber) {
        let state = this.state
        let evaNumberLi = this.selectorEle('.' + state.pageNumberCName, true)
        let len = evaNumberLi.length
        if (!len || this.isIllegal(pageNumber)) return
        // 清除 active 样式
        this.removeClass(this.selectorEle(`.${state.pCName}.${state.activeCName}`), state.activeCName)
        if (state.activePosition) {
            let rEllipseSign = state.totalPageCount - (state.maxShowBtnCount - state.activePosition) - 1
            // 左边不需要出现省略符号占位
            if (pageNumber <= state.maxShowBtnCount && (pageNumber < rEllipseSign)) {
                if (+evaNumberLi[1].getAttribute(state.dataNumberAttr) > 2) {
                    for (let i = 1; i < state.maxShowBtnCount + 1; i++) {
                        evaNumberLi[i].innerText = i + 1
                        evaNumberLi[i].setAttribute(state.dataNumberAttr, i + 1)
                    }
                }
                this.hiddenEllipse('.ellipsis-head')
                this.hiddenEllipse('.ellipsis-tail', false)
                this.addClass(evaNumberLi[pageNumber - 1], state.activeCName)
            }
            // 两边都需要出现省略符号占位
            if (pageNumber > state.maxShowBtnCount && pageNumber < rEllipseSign) {
                // 针对 maxShowBtnCount===1 的特殊处理
                this.hiddenEllipse('.ellipsis-head', pageNumber === 2 && state.maxShowBtnCount === 1)
                this.hiddenEllipse('.ellipsis-tail', false)
                for (let i = 1; i < state.maxShowBtnCount + 1; i++) {
                    evaNumberLi[i].innerText = pageNumber + (i - state.activePosition)
                    evaNumberLi[i].setAttribute(state.dataNumberAttr, pageNumber + (i - state.activePosition))
                }
                this.addClass(evaNumberLi[state.activePosition], state.activeCName)
            }
            // 右边不需要出现省略符号占位
            if (pageNumber >= rEllipseSign) {
                this.hiddenEllipse('.ellipsis-tail')
                this.hiddenEllipse('.ellipsis-head', false)
                if (+evaNumberLi[len - 2].getAttribute(state.dataNumberAttr) < state.totalPageCount - 1) {
                    for (let i = 1; i < state.maxShowBtnCount + 1; i++) {
                        evaNumberLi[i].innerText = state.totalPageCount - (state.maxShowBtnCount - i) - 1
                        evaNumberLi[i].setAttribute(state.dataNumberAttr, state.totalPageCount - (state.maxShowBtnCount - i) - 1)
                    }
                }
                this.addClass(evaNumberLi[(state.maxShowBtnCount + 1) - (state.totalPageCount - pageNumber)], state.activeCName)
            }
        } else {
            // 不需要省略符号占位
            this.addClass(evaNumberLi[pageNumber - 1], state.activeCName)
        }
        state.pageNumber = pageNumber
        state.onPageChange && state.onPageChange(state)
        // 判断 上一页 下一页 是否可使用
        this.switchPrevNextAble()
    }

    switchPrevNextAble() {
        let state = this.state
        let prevBtn = this.selectorEle('.' + state.prevCName)
        let nextBtn = this.selectorEle('.' + state.nextCName)
        // 当前页已经是第一页，则禁止 上一页 按钮的可用性
        state.pageNumber > 1 ?
            (this.hasClass(prevBtn, state.disbalePrevCName) && this.removeClass(prevBtn, state.disbalePrevCName)) :
            (!this.hasClass(prevBtn, state.disbalePrevCName) && this.addClass(prevBtn, state.disbalePrevCName))
        // 当前页已经是最后一页，则禁止 下一页 按钮的可用性
        state.pageNumber >= state.totalPageCount ?
            (!this.hasClass(nextBtn, state.disbaleNextCName) && this.addClass(nextBtn, state.disbaleNextCName)) :
            (this.hasClass(nextBtn, state.disbaleNextCName) && this.removeClass(nextBtn, state.disbaleNextCName))
    }

    renderPageDOM() {
        // 渲染页码DOM
        let state = this.state
        let pageContainer = this.selectorEle(state.container)
        if (!pageContainer) return
        let {
            totalPageCount,
            pCName,
            prevCName,
            disbalePrevCName,
            pageNumberCName,
            activeCName,
            dataNumberAttr,
            maxShowBtnCount,
            nextCName,
            disbaleNextCName
        } = state
        let paginationStr = `
                        <ul class="pagination">
                        <li class="${pCName} ${prevCName} ${disbalePrevCName}">上一页</li>
                        <li class="${pCName} ${pageNumberCName} ${activeCName}" ${dataNumberAttr}='1'>1</li>
                        `
                                if (totalPageCount - 2 > maxShowBtnCount) {
                                    paginationStr += `
                        <li class="${pCName} number-ellipsis ellipsis-head" style="display: none;">...</li>`
                                    for (let i = 2; i < maxShowBtnCount + 2; i++) {
                                        paginationStr += `<li class="${pCName} ${pageNumberCName} ${i === 1 ? activeCName : ''}" ${dataNumberAttr}='${i}'>${i}</li>`
                                    }
                                    paginationStr += `
                        <li class="${pCName} number-ellipsis ellipsis-tail">...</li>
                        <li class="${pCName} ${pageNumberCName}" ${dataNumberAttr}='${totalPageCount}'>${totalPageCount}</li>
                        `
        } else {
            for (let i = 2; i <= totalPageCount; i++) {
                paginationStr += `<li class="${pCName} ${pageNumberCName}" ${dataNumberAttr}='${i}'>${i}</li>`
            }
        }
        paginationStr += `<li class="${pCName} ${nextCName}${totalPageCount === 1 ? ' ' + disbaleNextCName : ''}">下一页</li></ul>`
        pageContainer.innerHTML = paginationStr
        // 切换页码
        this.switchPage()
    }

    isIllegal(pageNumber) {
        let state = this.state
        return (
            state.pageNumber === pageNumber || Math.ceil(pageNumber) !== pageNumber ||
            pageNumber > state.totalPageCount || pageNumber < 1 ||
            typeof pageNumber !== 'number' || pageNumber !== pageNumber
        )
    }

    hiddenEllipse(selector, shouldHidden = true) {
        this.selectorEle(selector).style.display = shouldHidden ? 'none' : ''
    }

    selectorEle(selector, all = false) {
        return all ? document.querySelectorAll(selector) : document.querySelector(selector)
    }

    hasClass(eleObj, className) {
        return eleObj.classList.contains(className);
    }

    addClass(eleObj, className) {
        eleObj.classList.add(className);
    }

    removeClass(eleObj, className) {
        if (this.hasClass(eleObj, className)) {
            eleObj.classList.remove(className);
        }
    }
}
const totalss = localStorage.getItem('totalss');
console.log(totalss);
const slp = new SimplePagination(totalss);
slp.init({
    container: '.boxs',
    maxShowBtnCount: 3,
    onPageChange: state => {
        getPage(state.pageNumber);
        // console.log('pagination change:', state.pageNumber)
    }
})
// document.getElementById('page-go').addEventListener('submit', e => {
//     e.preventDefault()
//     slp.gotoPage(+document.getElementById('page-num').value)
// })